#include <iostream>
#include <thread>
#include <mutex>
std::mutex mutex;

// mutex的使用
void test(int &num)
{
	mutex.lock();
	for (int i = 0; i < 500000; i++)
	{
		num++;
	}
	mutex.unlock();
}

void test1()
{
	int ans = 0;
	std::thread t1(test, std::ref(ans));
	std::thread t2(test, std::ref(ans));

	t1.join();
	t2.join();
	std::cout << ans << std::endl;
}

// lockguard的使用
void test2(int &num)
{
	std::lock_guard<std::mutex> lg(mutex);
	for (int i = 0; i < 500000; i++)
	{
		num++;
	}
}

void test3()
{
	int ans = 0;
	std::thread t1(test2, std::ref(ans));
	std::thread t2(test2, std::ref(ans));

	t1.join();
	t2.join();
	std::cout << ans << std::endl;
}


int main()
{
	// test1();
	//test3();
}